

/**
 * 详情对话框
 */
var InfoDlg = {
    data: {
        isCheck: null,
        ids: null
    }
};


layui.use(['form', 'table', 'admin', 'tree', 'ax'], function () {
    var $ = layui.$;
    var form = layui.form;
    var table = layui.table;
    var tree = layui.tree;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 系统管理--用户管理
     */
    var User = {
        tableId: "userTable",
        condition: {
            deptId: null,
            searchWords: null
        }
    };

    /**
     * 初始化表格的列
     */
    User.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'account', sort: true, title: '账号', width: '10%'},
            {field: 'name', sort: true, title: '姓名', width: '10%'},
            {field: 'sex', sort: true, title: '性别', width: '8%', templet: function (d) {
                var str = '男';
                if(d.sex == 2){
                    str = '女';
                }
                return str;
            }},
            {field: 'deptName', title: '机构', width: '10%'},
            {field: 'roleName', title: '角色', width: '24%'},
            {field: 'status', sort: true, title: '状态', width: '10%', templet:function (d) {
                var str = '<input value="'+d.id+'" type="checkbox" name="status" lay-skin="switch" lay-filter="userStatus" lay-text="启用|禁用">';
                if(d.status == 1){
                    str = '<input value="'+d.id+'" type="checkbox" name="status" lay-skin="switch" lay-filter="userStatus" lay-text="启用|禁用" checked>';
                }
                return str;
            }},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 140}
        ]];
    };

    /**
     * 点击查询按钮
     */
    User.search = function () {
        var queryData = {};
        queryData['dept_id'] = User.condition.deptId;
        queryData['searchWords'] = $("#searchWords").val();
        table.reload(User.tableId, {where: queryData});
    };

    /**
     * 弹出添加
     */
    User.openAddUser = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加用户',
            area: ['50%', '80%'],
            content: Lu.ctxPath + '/system/user/toAdd',
            end: function () {
                Lu.adminOpenEnd(admin, tableReload);
            }
        });
    };

    /**
     * 点击编辑用户
     *
     * @param data 点击按钮时候的行数据
     */
    User.onUpdateUser = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改用户',
            area: ['50%', '80%'],
            content: Lu.ctxPath + '/system/user/toUpdate?id=' + data.id,
            end: function () {
                Lu.adminOpenEnd(admin, tableReload);
            }
        });
    };

    /**
     * 点击删除用户
     *
     * @param data 点击按钮时候的行数据
     */
    User.onDeleteUser = function (data) {
        var operation = function () {
            var ajax = new $ax(Lu.ctxPath + "/system/user/delete", function () {
                Lu.success("删除成功!");
                tableReload();
            }, function (data) {
                Lu.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Lu.confirm("是否删除用户 " + data.name + "?", operation);
    };

    /**
     * 分配角色
     *
     * @param data 点击按钮时候的行数据
     */
    User.roleAssign = function (data) {
        var id = data.id;
        var isCheck = encodeURIComponent('parent.InfoDlg.data.isCheck');
        var ids = encodeURIComponent('parent.InfoDlg.data.ids');
        var treeUrl = encodeURIComponent('/system/user/roleTreeListByUserId/' + id);
        layer.open({
            type: 2,
            title: '角色分配',
            area: ['40%', '90%'],
            content: '/system/treeCheckNolinkage?isCheck='+isCheck+'&ids='+ids+'&treeUrl='+treeUrl+'',
            end: function () {
                var isCheck = InfoDlg.data.isCheck;
                var ids = InfoDlg.data.ids;
                if(isCheck && ids && isCheck == 1){
                    //给角色分配权限
                    var ajax = new $ax(Lu.ctxPath + "/system/user/setRole", function (data) {
                        Lu.success("分配角色成功!");
                        InfoDlg.data.isCheck = null;
                        InfoDlg.data.ids = null;
                    }, function (data) {
                        Lu.error("分配角色失败!" + data.responseJSON.message + "!");
                    });
                    ajax.set("roleIds", ids);
                    ajax.set("id", id);
                    ajax.start();
                }
            }
        });

    };


    /**
     * 重置密码
     *
     * @param data 点击按钮时候的行数据
     */
    User.resetPassword = function (data) {
        Lu.confirm("是否重置密码为111111 ?", function () {
            var ajax = new $ax(Lu.ctxPath + "/system/user/reset", function (data) {
                Lu.success("重置密码成功!");
            }, function (data) {
                Lu.error("重置密码失败!");
            });
            ajax.set("id", data.id);
            ajax.start();
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + User.tableId,
        url: Lu.ctxPath + '/system/user/listPage',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: User.initColumn()
    });

    var tableReload = () => {table.reload(User.tableId);};

    //layuiTree
    var treeAjax = new $ax(Lu.ctxPath + "/system/user/deptLayuiTreeByUser", function (data) {
        tree.render({
            elem: '#layuiTree'
            ,data: data
            ,onlyIconControl: true
            ,text: {
                defaultNodeName: '未命名'  //节点默认名称
                ,none: '无数据'            //数据为空时的提示文本
            }
            ,click: function(obj){
                User.condition.deptId = obj.data.id;
                User.search();
            }
        });
    }, function (data) {
        Lu.error("机构树获取失败!" + data.responseJSON.message + "!");
    });
    treeAjax.type = 'GET';
    treeAjax.start();

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        User.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        User.openAddUser();
    });

    // 工具条点击事件
    table.on('tool(' + User.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'update') {
            User.onUpdateUser(data);
        } else if (layEvent === 'delete') {
            User.onDeleteUser(data);
        } else if (layEvent === 'roleAssign') {
            User.roleAssign(data);
        } else if (layEvent === 'reset') {
            User.resetPassword(data);
        }
    });

    // 修改user状态
    form.on('switch(userStatus)', function (data) {
        var id = data.value;
        var status = 0;
        if(data.elem.checked){
            status=1;
        }
        var ajax = new $ax(Lu.ctxPath + "/system/user/update", function (data) {
            Lu.success("操作成功！");
        }, function (data) {
            Lu.error("操作失败！" + data.responseJSON.message)
        });
        ajax.set({id : id, status : status});
        ajax.start();
    });

});
